package com.tz.controller;

import com.tz.entity.Research;
import com.tz.entity.ResearchDetail;
import com.tz.entity.ResearchTemplate;
import com.tz.entity.json.AnswerJson;
import com.tz.service.ClazzService;
import com.tz.service.ResearchDetailService;
import com.tz.service.ResearchService;
import com.tz.service.ResearchTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;

/**
 * QuestionCategoryMapper
 * research 添加detailid
 *
 * @author Alex
 * @date 18/1/7
 */
@Controller
@RequestMapping("/prv")
public class PreviewController {
    private final ResearchTemplateService researchTemplateService;
    private final ResearchService researchService;
    private final ResearchDetailService researchDetailService;

    @Autowired
    public PreviewController(ResearchTemplateService researchTemplateService, ResearchService researchService, ResearchDetailService researchDetailService, ClazzService clazzService) {
        this.researchTemplateService = researchTemplateService;
        this.researchService = researchService;
        this.researchDetailService = researchDetailService;
    }


    @RequestMapping("/research")
    public String showResearch(HttpServletRequest request, Model model, @RequestParam("id") Long id) throws UnsupportedEncodingException {
        Research research = researchService.findById(id);
        if (research != null) {
            String remoteAddr = getIpaddress(request);
            if (canDoResearch(research.getClazz().getIpaddress(), remoteAddr, id)) {
                if (research.getState() == 0) {
                    model.addAttribute("username", research.getUser().getUsername());
                    model.addAttribute("clazzname", research.getClazz().getClazzname());
                    ResearchTemplate researchTemplate = researchTemplateService.getResearchTemplate(researchService.getTempIDbyResearchID(id));
                    model.addAttribute("cate", researchTemplate.getQuestioncategories());
                    model.addAttribute("adv", researchTemplate.getResearchadvices());
                    model.addAttribute("researchid", id);
                    HashMap<Long, int[]> obj = (HashMap<Long, int[]>) request.getServletContext().getAttribute("countMap");
                    //加锁防止并发
                    HashMap<Long, List<String>> ipMap = (HashMap<Long, List<String>>) request.getServletContext().getAttribute("ipMap");

                    synchronized (ipMap) {
                        if (ipMap.get(id) != null && !ipMap.get(id).contains(remoteAddr)) {
                            ipMap.get(id).add(remoteAddr);
                            synchronized (obj) {
                                obj.get(id)[0]++;
                            }
                        }
                    }


                    return "preview";
                }
            }
        }


        model.addAttribute("info", 2);
        return "redirect:/login/prelogin";
    }

    private boolean canDoResearch(String tagetIp, String nowIp, Long researchid) {
        String[] now = nowIp.split("\\.");
        String[] taget = tagetIp.split("\\.");

        if (now.length >= taget.length) {
            boolean isTarget = true;
            for (int i = 0; i < taget.length; i++) {

                if (!taget[i].equals(now[i])) {
                    isTarget = false;
                }
            }

            if (isTarget || tagetIp.equals("")) {
                if (researchDetailService.didThisResearch(researchid, nowIp) == 0) {
                    return true;
                } else {
                    System.out.println("地址提交过");
                }
            }

        }

        return false;
    }

    private String getIpaddress(HttpServletRequest request) {
        String remoteAddr = "";
        if (request != null) {
            remoteAddr = request.getHeader("X-FORWARDED-FOR");
            System.out.println(remoteAddr);
            if (remoteAddr == null || "".equals(remoteAddr)) {
                remoteAddr = request.getRemoteAddr();
                System.out.println(remoteAddr);
            }
        }
        return remoteAddr;
    }

    @ResponseBody
    @RequestMapping("/addDetail")
    public String addResearchDetail(HttpServletRequest request, @RequestBody AnswerJson answerJson) throws UnsupportedEncodingException {
        /*
         * 判断ip范围
         * 是否在范围并且还未调查
         */
        String remoteAddr = getIpaddress(request);

        if (canDoResearch("", remoteAddr, answerJson.getId())) {
            System.out.println("diyici");
            System.out.println(answerJson);
            ResearchDetail researchDetail = new ResearchDetail();
            researchDetail.setIpaddress(remoteAddr);
            researchDetail.setPolls(answerJson.getPolls());
            HashMap<Long, int[]> obj = (HashMap<Long, int[]>) request.getServletContext().getAttribute("countMap");
            if (obj.containsKey(answerJson.getId())) {
                //加锁防止并发
                synchronized (obj) {
                    obj.get(answerJson.getId())[1]++;
                }
                researchDetailService.addResearchDetail(answerJson.getId(), researchDetail);
                return "ok";
            } else {
                return "w";
            }


        } else {
            return "x";
        }


    }


}
